package com.carey.blog.tencent.microblog.oauth;

import com.carey.blog.framework.latke.repository.Transaction;
import com.carey.blog.framework.latke.util.Strings;
import com.carey.blog.libs.qweibo.OauthKey;
import com.carey.blog.libs.qweibo.QWeiboSyncApi;
import com.carey.blog.model.Preference;
import com.carey.blog.repository.impl.PreferenceGAERepository;
import com.carey.blog.util.Preferences;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

/**
 * OAuth servlet.
 * 
 */
public final class AuthorizeToken extends HttpServlet {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(AuthorizeToken.class
			.getName());
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		LOGGER.fine("GetRequestToken....");

		final String appKey = request.getParameter("appKey");
		final String appSecret = request.getParameter("appSecret");

		if (Strings.isEmptyOrNull(appKey) || Strings.isEmptyOrNull(appSecret)) {
			LOGGER.info("App key or secret empty!");

			return;
		}

		final JSONObject preference = preferenceUtils.getPreference();
		final String blogHost = preference.optString(Preference.BLOG_HOST);

		final QWeiboSyncApi api = new QWeiboSyncApi();
		final String callbackURL = "http://" + blogHost
				+ "/tencent-microblog-oauth-callback.do";
		final String resp = api.getRequestToken(appKey, appSecret, callbackURL);

		LOGGER.log(Level.FINE, "callbackURL[{0}]", callbackURL);
		LOGGER.log(Level.FINE, "Response[{0}]", resp);

		final OauthKey oauthKey = parseToken(resp);
		if (null == oauthKey) {
			return;
		}

		final Transaction transaction = PreferenceGAERepository.getInstance()
				.beginTransaction();
		try {
			preference.put(Preference.TENCENT_MICROBLOG_APP_KEY, appKey);
			preference.put(Preference.TENCENT_MICROBLOG_APP_SECRET, appSecret);
			preference.put(Preference.TENCENT_MICROBLOG_TOKEN_KEY,
					oauthKey.tokenKey);
			preference.put(Preference.TENCENT_MICROBLOG_TOKEN_SECRET,
					oauthKey.tokenSecret);

			preferenceUtils.setPreference(preference);
			transaction.commit();
		} catch (final Exception e) {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			LOGGER.log(Level.SEVERE, e.getMessage(), e);

			return;
		}

		response.sendRedirect("https://open.t.qq.com/cgi-bin/authorize?oauth_token="
				+ oauthKey.tokenKey);
	}

	/**
	 * Parses token and secret with the specified response.
	 * 
	 * @param response
	 *            the specified response
	 * @return oauth key, returns {@code null} if parse fail
	 */
	static OauthKey parseToken(final String response) {
		if (response == null || response.equals("")) {
			return null;
		}

		final String[] tokenArray = response.split("&");

		if (tokenArray.length < 2) {
			return null;
		}

		final String strTokenKey = tokenArray[0];
		final String strTokenSecret = tokenArray[1];

		final String[] token1 = strTokenKey.split("=");
		if (token1.length < 2) {
			return null;
		}

		final OauthKey ret = new OauthKey();
		ret.tokenKey = token1[1];

		final String[] token2 = strTokenSecret.split("=");
		if (token2.length < 2) {
			return null;
		}
		ret.tokenSecret = token2[1];

		LOGGER.log(Level.FINER, "Token[key={0}, secrect={1}]", new Object[] {
				ret.tokenKey, ret.tokenSecret });

		return ret;
	}
}
